package controller.servlets;

import dao.AthleteInformationDao;
import dao.SignUpRecordDao;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import modle.Athlete;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet(name = "AddSignUpItemServlet", value = "/addSignUpItem")
public class AddSignUpItemServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        SignUpRecordDao signUpRecordDao = new SignUpRecordDao();
        AthleteInformationDao athleteInformation = new AthleteInformationDao();
        //根据用户名更新数据库中的密码
        String birthday = request.getParameter("birthday");
        String phone = request.getParameter("phone");
        String project = request.getParameter("project");
        String bestgrade = request.getParameter("bestgrade");
        if(birthday == null || phone == null || project == null || bestgrade == null || project == "" || bestgrade == ""){
            out.print("{\"code\": -1, \"msg\": \"\"}");
            out.flush();
            return;
        }
        // 通过HttpServletRequest对象获取Session对象
        HttpSession session = request.getSession();
        Athlete athlete = (Athlete)session.getAttribute("role");
        try {
            Date date = new SimpleDateFormat("yyyy-MM-dd").parse(birthday);
            ((Athlete) session.getAttribute("role")).setBirthDate(date);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        ((Athlete) session.getAttribute("role")).setTel(phone);
        int id = athlete.getId();

        boolean isUpdate = athleteInformation.updateTel_Bir(phone,birthday,id);
        boolean isInsert = signUpRecordDao.insertRecord(Integer.parseInt(project),id,bestgrade);
        if(isUpdate && isInsert)
            out.print("{\"code\": 200, \"msg\": \"\"}");
        else if (isUpdate)
            out.print("{\"code\": 1, \"msg\": \"\"}");
        else if (isInsert)
            out.print("{\"code\": 2, \"msg\": \"\"}");
        else
            out.print("{\"code\": 3, \"msg\": \"\"}");
        out.flush();
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
